<script lang="ts" setup>
import { ref } from 'vue'
import { toNumber } from 'lodash-es'
import { ElMessage, ElMessageBox } from 'element-plus'
import { GetData, PostCopy, PostRefresh } from '@/api/modules/screen'

// const imgDomain = 'https://img1.eprhan.cc'
const router = useRouter()

const findFrom = ref({
  Name: '',
  MachineCode: '',
  Vid: '',
  DrawId: '',
})
const dataList: any = reactive({
  list: [],
  option: [],
})
const loading = ref(false)
const total = ref(0)
let PageSize = 20
let PageNum = toNumber(localStorage.getItem('currentPage')) || 1

async function GetDataList(PageIndex: number = 1, PageSize: number = 20) {
  loading.value = true
  const params = {
    PageIndex,
    PageSize,
    ...(findFrom.value.Name && ({ Name: findFrom.value.Name })),
    ...(findFrom.value.MachineCode && ({ Flag: findFrom.value.MachineCode })),
    ...(findFrom.value.Vid && ({ Vid: findFrom.value.Vid })),
    ...(findFrom.value.DrawId && ({ DrawId: findFrom.value.DrawId })),
  }
  await GetData(params).then(async (dataRes: any) => {
    if (dataRes.succeeded) {
      dataList.list = dataRes.data.items
      dataList.list = dataList.list.map((item: any) => ({
        ...item,
        bannerJson: (item.bannerJson as string).replace(/[[\]"]/g, '').split(','),
      }))
      total.value = dataRes.data.total
      loading.value = false
    }
  })
  loading.value = false
}
// 查询
function Inquire() {
  GetDataList(1, PageSize)
}

// 添加
function AddData() {
  router.push({
    name: 'screenDetail',
  })
}
// 编辑
function EditData(id: number) {
  localStorage.setItem('currentPage', `${PageNum}`)
  router.push({
    name: 'screenDetail',
    query: {
      id,
    },
  })
}

// 刷新
function Refresh(vid: number) {
  PostRefresh(vid).then((res: any) => {
    if (res.succeeded) {
      ElMessage.success('刷新成功')
      GetDataList()
    }
    else {
      ElMessage.error(`刷新失败${res.errors}`)
    }
  })
}

function CopyData(id: number) {
  ElMessageBox.confirm(
    '确定要复制该信息吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      PostCopy(id).then((res: any) => {
        if (res.succeeded) {
          ElMessage.success('复制成功')
          GetDataList()
        }
        else {
          ElMessage.error(`复制失败${res.errors}`)
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消',
      })
    })
}

// 翻页
function handleSizeChange(val: number) {
  GetDataList(1, val)
  PageSize = val
}
function handleCurrentChange(val: number) {
  GetDataList(val, PageSize)
  PageNum = val
}

const nowPageNum = computed(() => {
  return toNumber(localStorage.getItem('currentPage')) || 1
})

onMounted(() => {
  if (localStorage.getItem('currentPage') !== null) {
    GetDataList(toNumber(localStorage.getItem('currentPage')), 20)
    localStorage.removeItem('currentPage')
  }
  else {
    GetDataList()
  }
})
</script>

<template>
  <div>
    <PageMain>
      <SearchBar :show-toggle="false">
        <div class="header">
          <el-form label-positio="right" label-width="auto">
            <div class="from">
              <el-form-item label="大屏名称">
                <el-input v-model="findFrom.Name" placeholder="请输入大屏名称" clearable @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="机器码">
                <el-input v-model="findFrom.MachineCode" placeholder="请输入机器码" clearable @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="企微用户ID">
                <el-input v-model="findFrom.Vid" placeholder="请输入企微用户ID" clearable @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="抽奖活动ID">
                <el-input v-model="findFrom.DrawId" placeholder="请输入抽奖活动ID" clearable @keyup.enter="Inquire" />
              </el-form-item>
            </div>
          </el-form>
          <div class="text-right">
            <el-button @click="Inquire">
              查询
            </el-button>
          </div>
        </div>
      </SearchBar>
      <ElDivider border-style="dashed" />
      <div class="mb-5 text-right">
        <el-button type="success" @click="AddData">
          添加
        </el-button>
      </div>
      <el-table v-loading="loading" :data="dataList.list" stripe style="width: 100%;" border>
        <el-table-column align="center" prop="id" label="ID" width="100" />
        <el-table-column header-align="center" prop="name" label="大屏名称" width="400" />
        <el-table-column header-align="center" prop="machineCode" label="机器码" width="150" />
        <el-table-column header-align="center" prop="vid" label="企微用户id" width="200" />
        <el-table-column header-align="center" prop="drawId" label="抽奖活动id" width="180" />
        <el-table-column align="center" label="背景图" width="350">
          <template #default="scope">
            <el-scrollbar>
              <div class="scrollbar-flex-content">
                <el-image v-for="(item, index) in scope.row.bannerJson" :key="index" class="scrollbar-flex-img" :src="item" />
              </div>
            </el-scrollbar>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" fixed="right" min-width="250">
          <template #default="scope">
            <el-button type="primary" @click="EditData(scope.row.id)">
              编辑
            </el-button>
            <el-button type="primary" @click="Refresh(scope.row.vid)">
              刷新
            </el-button>
            <el-button type="success" @click="CopyData(scope.row.id)">
              复制
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="height: 10px;" />
      <el-pagination
        :default-page-size="20"
        :page-sizes="[5, 10, 20, 50, 100]"
        layout="total, sizes, ->, prev, pager, next, jumper"
        :total="total"
        :default-current-page="nowPageNum"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </PageMain>
  </div>
</template>

<style scoped>
.header {
  display: grid;
  grid-template-columns: 6fr 1fr;

  .from {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    grid-gap: 20px;

    .el-form-item {
      margin-bottom: 0;
    }
  }
}

.scrollbar-flex-content {
  display: flex;
  max-width: 300px;

  .scrollbar-flex-img {
    display: flex;
    flex-shrink: 0;
    align-items: center;
    justify-content: center;
    width: 100px;
    height: 120px;
    margin-right: 10px;
  }
}
</style>
